import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/pages/login/Login'
import Home from '@/pages/home/Home'
import Users from '@/pages/user/Users'
import Welcome from '@/components/welcome/Welcome'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  {
    path: '/login',
    component: Login,
    beforeEnter: (to, from, next) => {
      const tokenStr = window.sessionStorage.getItem('token')
      if (to.path === '/login') {
        if (tokenStr) return next('/home')
      }
      next()
    }
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 登录拦截，sessionStorage有token才能访问其他路由
// 否则，将进入登录页
router.beforeEach((to, form, next) => {
  // 访问登录页，直接放行
  if (to.path === '/login') return next()
  // 从 sessionStorage 中取出保存的 token 值
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token，跳转到登录页
  if (!tokenStr) return next('/login')
  next()
})

export default router
